from odoo import api, fields, models, _


class InheritStockQuant(models.Model):
    _inherit = 'stock.quant'

    product_code = fields.Char(related="product_id.default_code", store=True)
    initial_qty = fields.Float(string="Initial Qty", compute="_compute_initial_qty", compute_sudo=True, store=True)

    @api.depends('lot_id')
    def _compute_initial_qty(self):
        for rec in self:
            move_lines = rec.get_inventory_history()
            if move_lines:
                # 按照 decoration-success 判断入库记录
                incoming_move_lines = move_lines.filtered(
                    lambda line: (line.location_usage not in ('internal', 'transit')) and
                                 (line.location_dest_usage in ('internal', 'transit'))
                )
                # 如果有入库记录
                if incoming_move_lines:
                    # 按日期排序取最早的入库记录
                    # earliest_move = incoming_move_lines.sorted(key=lambda line: line.date)
                    # earliest_move = earliest_move[0]  # 获取最早的入库记录
                    rec.initial_qty = rec.initial_qty = sum(incoming_move_lines.mapped('quantity'))

    def get_inventory_history(self):
        domain = [
            ('company_id', '=', self.env.company.id),
            ('product_id', '=', self.product_id.id),
            ('state', '=', 'done'),
            ('lot_id', '=', self.lot_id.id)
        ]

        # 使用 search 查询记录
        move_lines = self.env['stock.move.line'].search(domain)

        return move_lines
